#include <QWidgetList>
#include <QApplication>
#include "GlobPref.h"
#include "DataCell.h"
#include "WinMain.h"
#include "scImpl.h"

const QDateTime GlobPref::timeMinQ(QDate(1970, 1, 1), QTime(0, 0), Qt::UTC); // should be TIME_MIN
const QDateTime GlobPref::timeMaxQ(QDate(2038, 1, 19), QTime(3, 14, 07), Qt::UTC); // should be TIME_MAX

GlobPref * GlobPref::inst(0);

#define FCT "GlobPref::get"
GlobPref * GlobPref::get()
{
	if(inst)
		return inst;
	inst=new GlobPref();
	return inst;
}

#undef FCT
#define FCT "GlobPref::QtTimeSpec2Txt"
const char * GlobPref::QtTimeSpec2Txt(Qt::TimeSpec ts)
{
	switch(ts)
	{
	case Qt::LocalTime: return "loc";
	case Qt::UTC: return "UTC";
	case Qt::OffsetFromUTC: return "offUTC";
	}
	return "not a Qt::TimeSpec";
}

#undef FCT
#define FCT "GlobPref::GlobPref"
GlobPref::GlobPref() :
	wm(0), debugData(false)
{
	QDateTime qdt;
	qdt.setTimeSpec(Qt::UTC);
	qdt.setTime_t(TIME_MIN);
	if(qdt!=timeMinQ)
	{
		ostringstream os;
		os <<FCT<<": TIME_MIN!=timeMinQ "<<qdt<<" -> "<<timeMinQ;
		throw new AppException(os.str().c_str(), true);
	}
	qdt.setTime_t(TIME_MAX);
	if(qdt!=timeMaxQ)
	{
		ostringstream os;
		os <<FCT<<": TIME_MAX!=timeMaxQ "<<qdt<<" -> "<<timeMaxQ;
		throw new AppException(os.str().c_str(), true);
	}
}

#undef FCT
#define FCT "GlobPref::~GlobPref"
GlobPref::~GlobPref()
{
}

#undef FCT
#define FCT "GlobPref::getMainWindow"
WinMain * GlobPref::getMainWindow()
{
	if(wm)
		return wm;
	QWidgetList qwl(QApplication::topLevelWidgets());
	for(QWidgetList::iterator it(qwl.begin()); it!=qwl.end(); ++it)
	{
		wm=dynamic_cast<WinMain*>(*it);
        if(wm)
            break;
    }
	if(!wm)
		throw new AppException(FCT ": no MainWindow", true);
	return wm;
}
